package com.moyun.modelclass.app;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.DeviceUtils;
import com.hjq.http.EasyConfig;
import com.hjq.http.config.IRequestInterceptor;
import com.hjq.http.config.IRequestServer;
import com.hjq.http.model.HttpHeaders;
import com.hjq.http.model.HttpParams;
import com.hjq.http.request.HttpRequest;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.RequestServer;
import com.moyun.modelclass.http.api.CommonRequestBody;
import com.moyun.modelclass.http.model.RequestHandler;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.AES;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mmkv.MMKV;
import com.tencent.smtt.sdk.QbSdk;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 作者：Meteor
 * 日期：2022/2/49:25 下午
 * tip：
 */
public class BaseApplication extends Application {
    private MMKV initKv;
    private static Context sContext;

    public static Context getContext() {
        return sContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;
        MMKV.initialize(this);
        initKv = MMKV.defaultMMKV();
        if (initKv.decodeBool("isShowDialog", false)) {
            initTBS();
            initBaidu();
        }
        initEasyConfig();
        initRefreshLayout();
    }

    public void initEasyConfig() {
        IRequestServer server = new RequestServer();
        CommonRequestBody commonRequestBody = new CommonRequestBody();
        commonRequestBody.setSource("3");
        if (initKv.decodeBool("isShowDialog", false)) {
            commonRequestBody.setUuid(DeviceUtils.getUniqueDeviceId());
        }else {
            commonRequestBody.setUuid("");
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(20000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(20000, TimeUnit.MILLISECONDS);
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        EasyConfig.with(builder.build())
                // 是否打印日志
                //.setLogEnabled(BuildConfig.DEBUG)
                // 设置服务器配置
                .setServer(server)
                // 设置请求处理策略
                .setHandler(new RequestHandler(this))
                // 设置请求参数拦截器
                .setInterceptor(new IRequestInterceptor() {
                    @Override
                    public void interceptArguments(HttpRequest<?> httpRequest, HttpParams params, HttpHeaders headers) {
                        params.put("header", JSON.toJSON(commonRequestBody));

                        MMKV kv = MMKV.defaultMMKV();
                        String tokenInfo = kv.decodeString("userTokenInfo");
                        headers.put("token", tokenInfo == null ? "" : tokenInfo);
                        headers.put("encrypt", "encrypt");
                    }

                    @Override
                    public Request interceptRequest(HttpRequest<?> httpRequest, Request request) {
                        if (CommonConfiguration.getApiUrl().contains(request.url().host())) {
                            String aesKeyBytes = AES.encrypt(request.body().toString());
                            JSONObject requestBody = new JSONObject();
                            requestBody.put("request", aesKeyBytes);

                            // 创建RequestBody
                            RequestBody body = RequestBody.create(
                                    requestBody.toString(),
                                    MediaType.parse("application/json; charset=utf-8")
                            );

                            // 创建请求
                            request = new Request.Builder()
                                    .url(request.url())
                                    .post(body)
                                    .addHeader("encrypt", Objects.requireNonNull(request.header("encrypt")))
                                    .addHeader("token", Objects.requireNonNull(request.header("token")))
                                    .tag(request.tag())
                                    .build();
                        }
                        return request;
                    }
                })
                // 设置请求重试次数
                .setRetryCount(0)
                // 设置请求重试时间
                .setRetryTime(8000)
                .into();
    }

    private void initRefreshLayout() {
        //启用矢量图兼容
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
            @Override
            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                //全局设置（优先级最低）
                layout.setEnableFooterFollowWhenNoMoreData(true);
                layout.setEnableFooterTranslationContent(true);
                layout.setEnableScrollContentWhenRefreshed(false);
                layout.setEnableScrollContentWhenLoaded(true);
                layout.setEnableAutoLoadMore(true);
                layout.setEnableOverScrollDrag(false);
                layout.setEnableOverScrollBounce(false);
                layout.setEnableLoadMoreWhenContentNotFull(false);
                layout.setPrimaryColorsId(R.color.color_213a4f);
                layout.getLayout().setTag("close egg");
            }
        });
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context);
            }
        });
    }

    public void initTBS() {
        //x5内核初始化接口
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//                Logger.e("X5内核加载结果 onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
//                Logger.e("X5内核加载完成");
            }
        });
    }

    public void initBaidu() {
        // SDK初始化，该函数不会采集用户个人信息，也不会向百度移动统计后台上报数据
        StatService.init(this, (CommonConfiguration.isRelease ? "94aa72debf" : "f0f9f9d16a"), "");

        // 通过该接口可以控制敏感数据采集，true表示可以采集，false表示不可以采集，
        // 该方法一定要最优先调用，请在StatService.start(this)之前调用，采集这些数据可以帮助App运营人员更好的监控App的使用情况，
        // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true
        StatService.setAuthorizedState(this, true);
    }
}
